#!/usr/bin/env bash

set -ex
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

WORKSPACE=$(pwd)
YOSYS_CMD=${YOSYS_CMD:-/OpenROAD-flow-scripts/tools/install/yosys/bin/yosys}
OPENROAD_EXE=${OPENROAD_EXE:-/OpenROAD-flow-scripts/tools/install/OpenROAD/bin/openroad}
KLAYOUT_CMD=${KLAYOUT_CMD:-/usr/bin/klayout}

XSOCK=/tmp/.X11-unix
XAUTH=/tmp/.docker.xauth
xauth nlist :0 | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge -
ARGUMENTS=$@

if test -t 0; then
    DOCKER_INTERACTIVE=-ti
fi

# Most of these options below has to do with allowing to
# run the OpenROAD GUI from within Docker.
docker run -u $(id -u ${USER}):$(id -g ${USER}) \
 -e LIBGL_ALWAYS_SOFTWARE=1 \
 -e "QT_X11_NO_MITSHM=1" \
 -e XDG_RUNTIME_DIR=/tmp/xdg-run \
 -e DISPLAY=$DISPLAY \
 -e QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb \
 -v $XSOCK:$XSOCK \
 -v $XAUTH:$XAUTH \
 -e XAUTHORITY=$XAUTH \
 -e FLOW_HOME=/OpenROAD-flow-scripts/flow/ \
 -e MAKEFILES=/OpenROAD-flow-scripts/flow/Makefile \
 -e YOSYS_CMD=$YOSYS_CMD \
 -e OPENROAD_EXE=$OPENROAD_EXE \
 -e KLAYOUT_CMD=$KLAYOUT_CMD \
 -v $WORKSPACE:/OpenROAD-flow-scripts/flow \
 --network host \
 $DOCKER_INTERACTIVE \
 ${OR_IMAGE:-openroad/flow-ubuntu22.04-builder:latest} \
 bash -c "set -ex
 mkdir /tmp/xdg-run
 cd /OpenROAD-flow-scripts/flow
 $ARGUMENTS
"
